import "core-js/stable";
import "regenerator-runtime/runtime";
import Vue from "vue";
import "./antd.js";
import App from "./App.vue";
import moment from "moment";
import router from "./router";
import store from "./store";
import axios from "axios";
import VCharts from "v-charts";
Vue.use(VCharts);

// 开发环境则引入mockjs
process.env.API === "/api" && require("./mock/index.js");

Vue.prototype.$moment = moment; // 赋值使用
moment.locale("zh-cn"); // 需要汉化

Array.prototype.remove = function(val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

// 获取环境设置的接口地址
axios.defaults.baseURL = process.env.API;
axios.default.timeout = 1000 * 60 * 2;
// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem("Authorization");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加返回拦截器，判断是否401
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error && error.response) {
      const { status, statusText } = error.response;

      if (status === 401) {
        // token过期并且非登录页
        if (router.currentRoute.name !== "login") {
          sessionStorage.removeItem("Authorization");
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
          return false;
        }
      }

      return {
        data: {
          success: false,
          msg: `接口异常[${status}]：${statusText}`,
        },
      };
    }
    return {
      data: {
        success: false,
        msg: `接口异常`,
      },
    };
  }
);
Vue.prototype.$myaxios = axios;

new Vue({
  render: (h) => h(App),
  router,
  store,
}).$mount("#app");
